package com.pet.platform.service.impl;

import com.pet.platform.common.PageResult;
import com.pet.platform.dto.OrderDTO;
import com.pet.platform.entity.Order;
import com.pet.platform.entity.OrderItem;
import com.pet.platform.entity.Product;
import com.pet.platform.entity.User;
import com.pet.platform.entity.Address;
import com.pet.platform.enums.OrderStatus;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.mapper.OrderMapper;
import com.pet.platform.mapper.ProductMapper;
import com.pet.platform.mapper.OrderItemMapper;
import com.pet.platform.mapper.UserMapper;
import com.pet.platform.mapper.AddressMapper;
import com.pet.platform.service.OrderService;
import com.pet.platform.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;
    private final ProductMapper productMapper;
    private final OrderItemMapper orderItemMapper;
    private final UserMapper userMapper;
    private final AddressMapper addressMapper;

    @Override
    @Transactional
    public Order createOrder(OrderDTO orderDTO) {
        // 获取当前用户ID
        Long userId = SecurityUtil.getCurrentUserId();
        
        // 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalAmount(orderDTO.getTotalAmount());
        order.setStatus(OrderStatus.PENDING.name());
        order.setCreatedTime(LocalDateTime.now());
        order.setUpdatedTime(LocalDateTime.now());
        
        // 设置订单号
        order.setOrderNo(orderDTO.getOrderNo());
        
        // 设置地址ID、支付方式和备注
        order.setAddressId(orderDTO.getAddressId());
        order.setPaymentMethod(orderDTO.getPaymentMethod());
        order.setRemark(orderDTO.getRemark());
        
        // 保存订单
        orderMapper.insert(order);
        
        // 创建订单项
        List<OrderItem> orderItems = new ArrayList<>();
        orderDTO.getOrderItems().forEach(itemDTO -> {
            Product product = productMapper.findById(itemDTO.getProductId())
                .orElseThrow(() -> new BusinessException("商品不存在"));
            
            // 检查库存
            if (product.getStock() < itemDTO.getQuantity()) {
                throw new BusinessException("商品库存不足");
            }
            
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(itemDTO.getProductId());
            orderItem.setQuantity(itemDTO.getQuantity());
            orderItem.setPrice(itemDTO.getPrice());
            orderItem.setCreatedTime(LocalDateTime.now());
            orderItem.setUpdatedTime(LocalDateTime.now());
            
            orderItemMapper.insert(orderItem);
            orderItems.add(orderItem);
            
            // 更新商品库存
            product.setStock(product.getStock() - itemDTO.getQuantity());
            productMapper.updateStock(product);
        });
        
        order.setOrderItems(orderItems);
        return order;
    }

    @Override
    @Transactional
    public OrderDTO createOrderFromCart(Long userId, String shippingAddress, String shippingPhone, String shippingName) {
        throw new UnsupportedOperationException("Not implemented yet");
    }

    @Override
    public OrderDTO getOrderById(Long id) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        // 获取订单项
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(id);
        order.setOrderItems(orderItems);
        
        // 获取用户信息
        User user = userMapper.findById(order.getUserId());
        if (user != null) {
            // 将用户信息设置到返回的DTO中
            OrderDTO dto = convertToDTO(order);
            dto.setUsername(user.getUsername());
            return dto;
        }
            
        return convertToDTO(order);
    }

    @Override
    public PageResult<Order> getUserOrders(Long userId, Integer pageNum, Integer pageSize) {
        // 获取总数
        Long total = orderMapper.countByUserId(userId);
        
        // 获取分页数据
        List<Order> orders = orderMapper.findByUserId(userId, (pageNum - 1) * pageSize, pageSize);
        
        // 获取订单项
        orders.forEach(order -> {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
            order.setOrderItems(orderItems);
        });
        
        return new PageResult<>(total, orders);
    }

    @Override
    public PageResult<Order> getOrdersByUserIdAndStatus(Long userId, Integer status, Integer pageNum, Integer pageSize) {
        String statusStr = convertStatusToString(status);
        
        // 获取总数
        Long total = orderMapper.countByUserIdAndStatus(userId, statusStr);
        
        // 获取分页数据
        List<Order> orders = orderMapper.findByUserIdAndStatus(userId, statusStr, (pageNum - 1) * pageSize, pageSize);
        
        // 获取订单项
        orders.forEach(order -> {
            List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
            order.setOrderItems(orderItems);
        });
        
        return new PageResult<>(total, orders);
    }

    @Override
    public PageResult<OrderDTO> searchOrders(String keyword, Integer pageNum, Integer pageSize) {
        // 获取总数
        Long total = orderMapper.countByKeyword(keyword, null, null, null, null, null);
        
        // 获取分页数据
        List<Order> orders = orderMapper.findByKeyword(keyword, null, null, null, null, null, 
                                                      (pageNum - 1) * pageSize, pageSize);
        
        // 获取订单项并转换为DTO
        List<OrderDTO> orderDTOs = orders.stream()
            .map(order -> {
                try {
                    // 获取订单项
                    List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
                    order.setOrderItems(orderItems != null ? orderItems : new ArrayList<>());
                    
                    // 转换为DTO
                    OrderDTO dto = convertToDTO(order);
                    
                    // 获取用户信息
                    User user = userMapper.findById(order.getUserId());
                    if (user != null) {
                        dto.setUsername(user.getUsername());
                    }
                    
                    return dto;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
        
        return new PageResult<>(total, orderDTOs);
    }

    @Override
    @Transactional
    public OrderDTO updateOrderStatus(Long id, String status) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        order.setStatus(status);
        order.setUpdatedTime(LocalDateTime.now());
        
        orderMapper.updateStatus(id, status, order.getUpdatedTime());
        
        // 获取订单项
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(id);
        order.setOrderItems(orderItems != null ? orderItems : new ArrayList<>());
        
        return convertToDTO(order);
    }

    @Override
    @Transactional
    public void cancelOrder(Long id) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        if (!OrderStatus.PENDING.name().equals(order.getStatus())) {
            throw new BusinessException("只能取消待支付的订单");
        }
        
        // 恢复商品库存
        List<OrderItem> orderItems = orderItemMapper.findByOrderId(id);
        orderItems.forEach(item -> {
            Product product = productMapper.findById(item.getProductId())
                .orElseThrow(() -> new BusinessException("商品不存在"));
            product.setStock(product.getStock() + item.getQuantity());
            productMapper.updateStock(product);
        });
        
        order.setStatus(OrderStatus.CANCELLED.name());
        order.setUpdatedTime(LocalDateTime.now());
        orderMapper.updateStatus(id, order.getStatus(), order.getUpdatedTime());
    }

    @Override
    @Transactional
    public void deleteOrder(Long id) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        if (!OrderStatus.CANCELLED.name().equals(order.getStatus())) {
            throw new BusinessException("只能删除已取消的订单");
        }
        
        // 删除订单项
        orderItemMapper.deleteByOrderId(id);
        // 删除订单
        orderMapper.delete(id);
    }

    @Override
    @Transactional
    public void payOrder(Long id, String paymentMethod) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        // 检查订单状态
        if (!OrderStatus.PENDING.name().equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(OrderStatus.PAID.name());
        order.setUpdatedTime(LocalDateTime.now());
        
        orderMapper.updateStatus(id, order.getStatus(), order.getUpdatedTime());
    }

    @Override
    @Transactional
    public void confirmReceive(Long id) {
        Order order = orderMapper.findById(id)
            .orElseThrow(() -> new BusinessException("订单不存在"));
            
        // 检查订单状态
        if (!OrderStatus.SHIPPED.name().equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }
        
        // 更新订单状态
        order.setStatus(OrderStatus.COMPLETED.name());
        order.setUpdatedTime(LocalDateTime.now());
        
        orderMapper.updateStatus(id, order.getStatus(), order.getUpdatedTime());
    }

    @Override
    public Long count() {
        return orderMapper.count();
    }

    @Override
    public BigDecimal getTotalSales() {
        return orderMapper.getTotalSales();
    }

    @Override
    public List<OrderDTO> getLatestOrders(int limit) {
        try {
            List<Order> orders = orderMapper.findLatestOrders(limit);
            
            // 确保orders不为null
            if (orders == null) {
                return new ArrayList<>();
            }
            
            return orders.stream()
                .map(order -> {
                    try {
                        // 获取订单项
                        List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
                        order.setOrderItems(orderItems != null ? orderItems : new ArrayList<>());
                        return this.convertToDTO(order);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public PageResult<OrderDTO> advancedSearchOrders(
            String keyword, String orderNo, String username, 
            String status, String startDate, String endDate, 
            Integer pageNum, Integer pageSize) {
        
        // 转换日期字符串为LocalDateTime
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        try {
            if (startDate != null && !startDate.isEmpty()) {
                startDateTime = LocalDateTime.parse(startDate + "T00:00:00");
            }
            if (endDate != null && !endDate.isEmpty()) {
                endDateTime = LocalDateTime.parse(endDate + "T23:59:59");
            }
        } catch (Exception e) {
            throw new BusinessException("日期格式不正确，请使用yyyy-MM-dd格式");
        }
        
        // 获取总数
        Long total = orderMapper.countByKeyword(
            keyword, orderNo, username, status, startDateTime, endDateTime);
        
        // 获取分页数据
        List<Order> orders = orderMapper.findByKeyword(
            keyword, orderNo, username, status, startDateTime, endDateTime,
            (pageNum - 1) * pageSize, pageSize);
        
        // 获取订单项并转换为DTO
        List<OrderDTO> orderDTOs = orders.stream()
            .map(order -> {
                try {
                    // 获取订单项
                    List<OrderItem> orderItems = orderItemMapper.findByOrderId(order.getId());
                    order.setOrderItems(orderItems != null ? orderItems : new ArrayList<>());
                    
                    // 转换为DTO
                    OrderDTO dto = convertToDTO(order);
                    
                    // 获取用户信息
                    User user = userMapper.findById(order.getUserId());
                    if (user != null) {
                        dto.setUsername(user.getUsername());
                    }
                    
                    return dto;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            })
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
        
        return new PageResult<>(total, orderDTOs);
    }

    private OrderDTO convertToDTO(Order order) {
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setId(order.getId());
        orderDTO.setUserId(order.getUserId());
        orderDTO.setTotalAmount(order.getTotalAmount());
        orderDTO.setStatus(order.getStatus());
        orderDTO.setCreatedTime(order.getCreatedTime());
        orderDTO.setUpdatedTime(order.getUpdatedTime());
        
        // 设置新增的字段
        orderDTO.setOrderNo(order.getOrderNo());
        orderDTO.setAddressId(order.getAddressId());
        orderDTO.setPaymentMethod(order.getPaymentMethod());
        orderDTO.setRemark(order.getRemark());
        
        // 获取用户信息
        User user = userMapper.findById(order.getUserId());
        if (user != null) {
            orderDTO.setUsername(user.getUsername());
        }
        
        // 获取地址信息
        if (order.getAddressId() != null) {
            Address address = addressMapper.findById(order.getAddressId());
            if (address != null) {
                orderDTO.setReceiverName(address.getReceiverName());
                orderDTO.setReceiverPhone(address.getReceiverPhone());
                
                // 构建完整的地址字符串
                String fullAddress = address.getProvince() + " " + 
                                     address.getCity() + " " + 
                                     address.getDistrict() + " " + 
                                     address.getDetailAddress();
                orderDTO.setReceiverAddress(fullAddress);
            }
        }
        
        // 处理订单项可能为null的情况
        List<OrderDTO.OrderItemDTO> orderItemDTOs = new ArrayList<>();
        if (order.getOrderItems() != null) {
            orderItemDTOs = order.getOrderItems().stream()
                .map(item -> {
                    OrderDTO.OrderItemDTO itemDTO = new OrderDTO.OrderItemDTO();
                    itemDTO.setId(item.getId());
                    itemDTO.setProductId(item.getProductId());
                    itemDTO.setQuantity(item.getQuantity());
                    itemDTO.setPrice(item.getPrice());
                    
                    // 获取商品名称和图片URL
                    try {
                        Product product = productMapper.findById(item.getProductId()).orElse(null);
                        if (product != null) {
                            itemDTO.setProductName(product.getName());
                            itemDTO.setImageUrl(product.getImageUrl());
                        } else {
                            itemDTO.setProductName("未知商品");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        itemDTO.setProductName("未知商品");
                    }
                    
                    return itemDTO;
                })
                .collect(Collectors.toList());
        }
            
        orderDTO.setOrderItems(orderItemDTOs);
        return orderDTO;
    }

    private String convertStatusToString(Integer status) {
        switch (status) {
            case 0:
                return OrderStatus.PENDING.name();
            case 1:
                return OrderStatus.PAID.name();
            case 2:
                return OrderStatus.SHIPPED.name();
            case 3:
                return OrderStatus.COMPLETED.name();
            case 4:
                return OrderStatus.CANCELLED.name();
            default:
                throw new BusinessException("无效的订单状态");
        }
    }
} 